package com.campus.server.service;

import com.campus.common.type.BuyResult;
import com.campus.common.vo.BankAccount;
import com.campus.common.vo.Product;
import com.campus.server.dao.BankDao;
import com.campus.server.dao.ProductDao;
import java.util.List;

public class ShopService {
	private ProductDao dao = new ProductDao();
	private BankDao b_dao = new BankDao();
	
	public List<Product> listProducts() {
        return dao.listAllProducts();
    }
	
	public BuyResult buyProducts(List<Integer> productIds, List<Integer> quantities, String userId, String password) {
		if (productIds == null || quantities == null || productIds.size() != quantities.size()) {
	        throw new IllegalArgumentException("商品ID列表和数量列表不能为空且长度一致");
	    }
	    
	    BankAccount account = b_dao.findAccountById(userId);
        if (account == null || !account.getPassword().equals(password)) {
            return BuyResult.INCORRECT_PASSWORD; // 密码错误
        }

	    double total = 0;

	    // 先检查库存并计算总金额
	    for (int i = 0; i < productIds.size(); i++) {
	        int id = productIds.get(i);
	        int qty = quantities.get(i);

	        Product p = dao.findById(id);
	        if (p == null || p.getStock() < qty) {
	            return BuyResult.INSUFFICIENT_STOCK;
	        }
	        
	        double price = p.getPrice();
	        if(p.getExpireSoon() == 1) {
	        	price = price * 0.7;
	        }
	        total += price * qty;
	    }

	    BankService bankService = new BankService();
	    
	    // 调用 BankService 扣款（带密码校验）
	    boolean payOk = bankService.pay(userId, total, password);

	    if (!payOk) {
	        // 再次验证，区分具体错误原因
	        BankAccount acc = b_dao.findAccountById(userId);
	        if (acc == null || !acc.getPassword().equals(password)) {
	            return BuyResult.INCORRECT_PASSWORD;
	        } else {
	            return BuyResult.INSUFFICIENT_BALANCE;
	        }
	    }

	    // 扣款成功后再减少库存
	    for (int i = 0; i < productIds.size(); i++) {
	        dao.reduceStock(productIds.get(i), quantities.get(i));
	    }

	    return BuyResult.SUCCESS;
	}


	
	// 新增商品
	public boolean addNewProduct(Product p) {
	    return dao.insertProduct(p);
	}

	// 删除商品
	public boolean removeProduct(int id) {
	    return dao.deleteProductById(id);
	}

	// 修改商品信息
	public boolean modifyProduct(Product p) {
	    return dao.updateProductInfo(p);
	}

	// 修改商品状态
	public boolean setProductStatus(int id, int status) {
	    return dao.changeProductStatus(id, status);
	}
	
	// 修改商品是否热卖
	public boolean setProductHot(int id, int hot) {
	    return dao.changeProductHot(id, hot);
	}
	
	// 修改商品是否上新
	public boolean setProductNew(int id, int newP) {
	    return dao.changeProductNew(id, newP);
	}
		
	// 修改商品是否临期	
	public boolean setProductExpire(int id, int expire) {
	    return dao.changeProductExpire(id, expire);
	}

}

